package com.atuigu.crowd.filter;

import com.atguigu.crowd.util.AccessPassResources;
import com.atguigu.crowd.util.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CrowdAccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 这里返回“pre”意思是在目标微服务前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();

        // 通过RequestContext获取当前请求对象
        HttpServletRequest request = requestContext.getRequest();

        // 获取servletPath
        String servletPath = request.getServletPath();

        // 根据 servletPath 判断当前请求是否对应可以直接放行的特定功能
        boolean containsResult = AccessPassResources.PASS_RES_SETPAS.contains(servletPath);

        if (containsResult) {
            //如果当前请求是可以直接放行的特定功能请求则返回 false 放行
            return false;
        }
        // 5.判断当前请求是否为静态资源
        // 工具方法返回 true：说明当前请求是静态资源请求，取反为false 表示放行不做登录检查
        // 工具方法返回 false：说明当前请求不是可以放行的特定请求也不是静态资源，取反为 true 表示需要做登录检查
        return !AccessPassResources.judgeCurrentServletPathWhetherStaticResources(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        // 1.获取当前请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        // 2.获取当前 Session 对象
        HttpSession session = request.getSession();

        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (loginMember == null) {

            HttpServletResponse response = requestContext.getResponse();

            //将提示消息存入 Session 域
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_FORBIDEN);

            // 重定向到 auth-consumer 工程中的登录页面
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
